#include <iostream>
#include <vector>
#include <map>
using namespace std;

class Solution
{
public:
    int largestInteger(vector<int> &nums, int k)
    {
        if (k == nums.size())
        {
            return *max_element(nums.begin(), nums.end());
        }
        if (k == 1)
        {
            map<int, int> pq;
            for (int i = 0; i < nums.size(); i++)
            {
                if (pq.find(nums[i]) == pq.end())
                    pq[nums[i]] = 0;
                pq[nums[i]]++;
            }
            int maxnum = -1;
            for (auto i : pq)
            {
                if (i.second == 1)
                {
                    maxnum = max(maxnum, i.first);
                }
            }
            return maxnum;
        }
        bool start = true, end = true;
        if (nums[nums.size() - 1] == nums[0])
        {
            return -1;
        }
        for (int i = 1; i < nums.size() - 1; i++)
        {
            if (nums[i] == nums[0])
            {
                start = false;
            }
            if (nums[i] == nums[nums.size() - 1])
            {
                end = false;
            }
            if (!start && !end)
            {
                return -1;
            }
        }
        if (start && end)
        {
            return max(nums[0], nums[nums.size() - 1]);
        }
        else if (start)
        {
            return nums[0];
        }
        else if (end)
        {
            return nums[nums.size() - 1];
        }
        else
        {
            return -1;
        }
    }
};

int main()
{
    cout << "Code3471" << endl;
    Solution s;
    // vector<int> nums = {3, 9, 7, 2, 1, 7};
    // vector<int> nums = {0, 0, 0, 1, 0};
    vector<int> nums = {4, 4, 2, 3, 5, 6, 4, 4};
    cout << s.largestInteger(nums, 3) << endl;
    return 0;
}